import { createSelectBox } from "../utils/utils.js"
import { HeaderComponent } from "./header.js"
import { colorList, commonColorList } from "../../config/index.js"
import { setCursorToPosition } from "../utils/edit.js"
import { Tooltip } from "../utils/tooltip.js"
window.addEventListener('DOMContentLoaded', function () {
    const header = new HeaderComponent()
    const page = new RichTextEditorPage(header)
    //语言切换方法
    header.languageFn = page.createContainer.bind(page)
    page.createContainer()
    new Tooltip()
})
class RichTextEditorPage {
    // 工具栏元素
    #toolbar = document.getElementsByClassName("editor-container-toolbar")[0]
    //输入框元素
    #inputMain = document.getElementById("editor-container-main")
    //编辑器占位内容
    #emptyMain = '<p data-placeholder="点击输入内容..." id="is-empty"></p>'
    createContainer() {
        this.#createGetHTMLBtn()
        this.#createSeparator()
        this.#createFamilyToolbar()
        this.#createSeparator()
        this.#createColorToolbar()
        this.#createSeparator()
        this.#createBlodFontToolbar()
        this.#createItalicFontToolbar()
        this.#createUnderLineFontToolbar()
        //工具栏点击事件
        this.#toolbar.addEventListener('click', this.#toolbarEvent.bind(this))
        //编辑器输入事件
        this.#inputMain.addEventListener('input', this.#editInputHandler.bind(this))
        //编辑器粘贴事件
        this.#inputMain.addEventListener('paste', this.#editPasteHandler.bind(this))
        //编辑器键盘事件
        this.#inputMain.addEventListener('keydown', this.#editKeyDownHandler.bind(this))
    }
    //获取编辑器HTML
    #getMainHTML() {
        console.log(this.#inputMain.innerHTML)
    }
    //创建获取编辑器内容按钮
    #createGetHTMLBtn() {
        const dom = document.createElement("button")
        dom.className = "editor-container-toolbar-item"
        dom.innerText = "获取内容"
        dom.setAttribute("data-type", "getHTML")
        dom.setAttribute("tooltip-popover", "true")
        dom.setAttribute("tooltip-text", "获取编辑器HTML")
        dom.style.textAlign = "center"
        this.#toolbar.appendChild(dom)
    }
    //创建字体工具栏
    #createFamilyToolbar() {
        const dom = createSelectBox({
            list: [{ label: "默认字体", value: 1 }],
            className: "editor-container-toolbar-item",
            defValue: 1
        })
        this.#toolbar.appendChild(dom)
    }
    //创建调色工具栏
    #createColorToolbar() {
        const section = document.createElement("div")
        section.setAttribute("class", "color-container")
        const commonColors = document.createElement("div")
        const fragment = document.createDocumentFragment()
        //默认颜色
        const colorStr = colorList.map(item => {
            const child = item.shades.map(item => {
                return `<button style="background:${item}" data-type=foreColor data-value="${item}" class=color-item></button>`
            }).join("")
            return `
            <div class=color-container-list>
                ${child}
            </div>
            `
        }).join("")
        // 常用颜色
        const commColors = commonColorList.map(item => {
            return `<button style="background:${item}" data-type=foreColor data-value="${item}" class=color-item></button>`
        }).join("")
        commonColors.innerHTML = `
        <div class=common-colors-tips><span>常用颜色</span></div>
        <div class="xdj-row common-colors">${commColors}</div>
        `
        section.innerHTML = colorStr
        const label = document.createElement("span")
        label.innerText = "字体颜色"
        fragment.append(section, commonColors)
        const dom = createSelectBox({
            customLabel: label,
            className: "editor-container-toolbar-item",
            flyoutClass: "color-flyout",
            defValue: 1,
            customDom: fragment
        })
        this.#toolbar.appendChild(dom)
    }
    //创建B字体
    #createBlodFontToolbar() {
        const dom = document.createElement("button")
        dom.className = "editor-container-toolbar-item"
        dom.innerText = "B"
        dom.style.fontWeight = "bold"
        dom.setAttribute("data-type", "bold")
        dom.setAttribute("tooltip-popover", "true")
        dom.setAttribute("tooltip-text", "加粗")
        dom.style.width = "20px"
        dom.style.textAlign = "center"
        this.#toolbar.appendChild(dom)
    }
    //创建斜体字体
    #createItalicFontToolbar() {
        const dom = document.createElement("button")
        dom.className = "editor-container-toolbar-item"
        dom.innerText = "I"
        dom.style.fontStyle = "italic"
        dom.setAttribute("data-type", "italic")
        dom.setAttribute("tooltip-popover", "true")
        dom.setAttribute("tooltip-text", "倾斜")
        dom.style.width = "20px"
        dom.style.textAlign = "center"
        this.#toolbar.appendChild(dom)
    }
    //创建下划线
    #createUnderLineFontToolbar() {
        const dom = document.createElement("button")
        dom.className = "editor-container-toolbar-item"
        dom.innerText = "U"
        dom.style.textDecoration = "underline"
        dom.setAttribute("data-type", "underline")
        dom.setAttribute("tooltip-popover", "true")
        dom.setAttribute("tooltip-text", "下划线")
        dom.style.width = "20px"
        dom.style.textAlign = "center"
        this.#toolbar.appendChild(dom)
    }
    //创建分隔栏
    #createSeparator() {
        const div = document.createElement("div")
        div.setAttribute("class", "editor-container-toolbar-separator")
        this.#toolbar.appendChild(div)
    }
    //键盘点击处理
    #editKeyDownHandler(e) {
        if (e.key === "Tab") {
            e.preventDefault(); // 阻止默认的Tab行为
            //缩进行
            document.execCommand("Indent", false, null);
        }
    }
    //清除占位内容
    #clearEmpty(target=this.#inputMain,text="") {
        const empty = document.getElementById("is-empty")
        if (empty) {
            target.removeChild(empty)
            if (text!=null) {
                target.innerHTML = '<p>' + text + '</p>'
                //设置光标位置
                setCursorToPosition(target.childNodes[0], text?1:0);
            }
        }
    }
    //样式清除处理
    #styleClearHandler(target,tagName){
        let p = target.querySelectorAll(tagName);
        //去掉所有属性
        p.forEach(item => {
            Array.from(item.attributes).forEach(attr => item.removeAttribute(attr.name));
        })
    }
    //编辑器粘贴处理
    #editPasteHandler(e) {
        const target = this.#inputMain
        setTimeout(() => {
            //清除一些粘贴内容的样式和标签
            if (target.innerHTML.includes('<div')) {
                target.innerHTML = target.innerHTML.replace(/<div/g, "<p").replace(/<\/div>/g, "</p>");
                this.#styleClearHandler(target,'p')
            }
            if (target.innerHTML.includes('<p')) {
                this.#styleClearHandler(target,'p')
            }
            if (target.innerHTML.includes('<blockquote')) {
                this.#styleClearHandler(target,'blockquote')
            }
        }, 500)
    }
    //编辑器输入处理
    #editInputHandler(e) {
        const target = e.target
        const data = e.data
        if (target.innerHTML === e.data) {
            //初始输入创建一个P标签
            target.innerHTML = '<p>' + e.data + '</p>'
            //设置光标位置
            setCursorToPosition(this.#inputMain.childNodes[0], e.data?1:0);
        } else if (target.innerHTML === "") {
            target.innerHTML = this.#emptyMain
        } else if (target.innerHTML !== "") {
            this.#clearEmpty(target,data)
        }
    }
    //文字调色处理
    #textColorChangeHandler({ selection, color }) {
        document.execCommand("foreColor", false, color);
        // 清除选中效果（可以不清除，根据需要）
        selection.removeAllRanges();
    }
    //文字strong样式处理
    #textStrongChangeHandler({ selection, type, text }) {
        document.execCommand(type, false, null);
        // 清除选中效果（可以不清除，根据需要）
        selection.removeAllRanges();
    }
    //文字em样式处理
    #textEmChangeHandler({ selection, type, text }) {
        document.execCommand(type, false, null);
        // 清除选中效果（可以不清除，根据需要）
        selection.removeAllRanges();
    }
    //文字下划线处理
    #fontUnderlineChangeHandler({ selection, type, text }) {
        document.execCommand(type, false, null);
        // 清除选中效果（可以不清除，根据需要）
        selection.removeAllRanges();
    }
    //工具栏点击事件
    #toolbarEvent(e) {
        const target = e.target
        const value = target.dataset.value
        const type = target.dataset.type
        if (type) {
            const selection = window.getSelection();//获取选区对象
            const text = window.getSelection().toString()//获取选取文本
            if (selection.rangeCount > 0) {
                // 确保选区有选中的文本
                const range = selection.getRangeAt(0); // 获取选中的文本范围
                switch (type) {
                    // 颜色
                    case "foreColor": this.#textColorChangeHandler({ selection, type, color: value }); break;
                    // 粗体
                    case "bold": this.#textStrongChangeHandler({ selection, type }); break;
                    // 斜体
                    case "italic": this.#textEmChangeHandler({ selection, type }); break;
                    //下划线
                    case "underline": this.#fontUnderlineChangeHandler({ selection, type }); break;
                    case "getHTML": this.#getMainHTML(); break;
                }
            }

        }
    }
}